<template>
  <px-config-provider :locale="currentLocale">
    <router-view />
  </px-config-provider>
</template>

<script lang="ts">
import { defineComponent } from "vue";
// import { checkVersion } from "version-rocket";
import { PxConfigProvider, PxMessage, PxMessageBox } from "px-ui";
// import en from "element-plus/dist/locale/en.mjs";
// import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import { useUserStoreHook } from "@/store/modules/user";
import en from "px-ui/dist/locale/en.mjs";
import zhCn from "px-ui/dist/locale/zh-cn.mjs";
import { router } from "@/router";

window.addEventListener("message", event => {
  if (event.data === "uacLogout") {
    useUserStoreHook().logOut();
    PxMessage({
      type: "error",
      message: "登录凭证无效!",
      onClose: () => {
        router.push("/all");
      }
    });
    return;
  }
  // 确保消息来源为pms
  if (event.origin !== import.meta.env.VITE_API_URL_PMS_NEW) return;
  if (JSON.parse(event.data)?.code === "TokenExpired") {
    useUserStoreHook().logOut();
    PxMessage({
      type: "error",
      message: "登录凭证无效!",
      onClose: () => {
        router.push("/all");
      }
    });
  }
});

// 检测新系统版本
window.addEventListener("unhandledrejection", event => {
  const error = event.reason;
  if (error instanceof TypeError && error.message.includes("Failed to fetch dynamically imported module")) {
    PxMessageBox.confirm("检测到系统版本已更新，请刷新后重试!", "提示", {
      showCancelButton: false,
      confirmButtonText: "确认",
      type: "warning",
      showClose: false
    })
      .then(async () => {
        window.location.reload();
      })
      .catch(() => {});
  }
});

export default defineComponent({
  name: "app",
  components: {
    [PxConfigProvider.name]: PxConfigProvider
  },
  computed: {
    currentLocale() {
      return this.$storage.locale?.locale === "zh" ? zhCn : en;
    }
  },
  beforeCreate() {
    // const { version, name: title } = __APP_INFO__.pkg;
    // const { VITE_PUBLIC_PATH, MODE } = import.meta.env;
    // // https://github.com/guMcrey/version-rocket/blob/main/README.zh-CN.md#api
    // if (MODE === "production") {
    //   // 版本实时更新检测，只作用于线上环境
    //   checkVersion(
    //     // config
    //     {
    //       // 5分钟检测一次版本
    //       pollingTime: 300000,
    //       localPackageVersion: version,
    //       originVersionFileUrl: `${location.origin}${VITE_PUBLIC_PATH}version.json`
    //     },
    //     // options
    //     {
    //       title,
    //       description: "检测到新版本",
    //       buttonText: "立即更新"
    //     }
    //   );
    // }
  }
});
</script>
